package com.atguigu.yygh.hosp.interceptor;

import com.alibaba.fastjson.JSON;
import com.atguigu.yygh.common.utils.MD5;
import com.atguigu.yygh.hosp.result.Result;
import com.atguigu.yygh.hosp.service.HospitalSetService;
import com.atguigu.yygh.model.hosp.HospitalSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import utils.HttpRequestHelper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

@Component
public class ApiInterceptor implements HandlerInterceptor {

    @Autowired
    private HospitalSetService hospitalSetService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取参数中的时间戳
        String timestamp = request.getParameter("timestamp");
        //判断时间差是否大于10s
        Long  mills=System.currentTimeMillis()-Long.parseLong(timestamp);



        if (mills>100000){
            Result<Object> message = Result.fail().message("请求调用超时,请重试");
            String jsonString = JSON.toJSONString(message);


            //获取输出流,响应字符串
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();

            //直接响应字符
            writer.write(jsonString);

            //拦截请求
            return false;
        }

        //获取参数中的签名
        String sign = request.getParameter("sign");

        //使用hoscode 查询预约平台中保存的签名
        String hoscode = request.getParameter("hoscode");
        String signDB=hospitalSetService.getSingKey(hoscode);

        //所有参数
        Map<String, String[]> parameterMap = request.getParameterMap();

        Map<String, Object> map = HttpRequestHelper.switchMap(parameterMap);

        //MD5加密所有参数
        String sign_MD5 = HttpRequestHelper.getSign(map, signDB);

        //MD5加密后对比

        if(!sign_MD5.equals(sign)){
            Result<Object> message = Result.fail().message("签名错误");
            String jsonString = JSON.toJSONString(message);

            //获取输出流,响应字符串
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();

            //直接响应字符
            writer.write(jsonString);

            //拦截请求
            return false;
        }
        return true;

    }


}
